// @ts-ignore
import wasmBinaryUrl from "./opuslibs.wasm";

async function fetchResource(url: string): Promise<boolean> {
    return new Promise<boolean>((resolve, reject) => {
        const xhr = new XMLHttpRequest();
        xhr.responseType = "blob";
        xhr.open('GET', url);
        xhr.onloadend = () => {
            if (xhr.readyState == XMLHttpRequest.DONE) {
                const reader = new FileReader();
                reader.onloadend = () => {
                    const urlStr: string = reader.result as string;
                    localStorage.setItem("WASMB", urlStr.substring(urlStr.indexOf(",") + 1));
                    resolve(true);
                };
                reader.onerror = () => {
                    reject('转化失败');
                };
                reader.readAsDataURL(xhr.response);
            }else {
                reject(new Error("获取资源失败:" + xhr.statusText));
            }
        };

        xhr.onerror = (e) => {
            reject(new Error("获取资源失败:" + xhr.statusText + e));
        };

        xhr.send();
    })
}

async function loadWasmBinary(): Promise<boolean> {
    return fetchResource(wasmBinaryUrl);
}

export {loadWasmBinary}